var DBObject = require('../dbobject.js').DBObject;


exports.HoroscopefarmTree = DBObject.extend({
    init: function() {
        this._super('horoscopefarm_tree');
    },

    getDB: function() {
        return gDBWorld;
    },

    getClassName: function() {
        return "HoroscopefarmTree";
    },

    reset: function() {
        this._super();
    },

    getUserData: function(uid) {
        var userData = this.get(uid);
        var now = new Date();
        if (!userData || now.getDayPassed(userData.lastStamp) != 1) {
            userData = {
                assistors: [],
                award: 0,
                lastStamp: now.getStamp(),
            }

            this.set(uid, userData);
            for (var key in userData) {
                this.markDirty(uid, key);
            }
            this.save();
        }
        return userData;
    },

    getUserInfo: function(uid) {
        var userData = this.getUserData(uid);

        var userInfo = {award: userData.award, assistors: [],};
        userData.assistors.forEach(function(uid) {
            var user = gUserInfo.getUser(uid);
            userInfo.assistors.push({uid: uid, name: user ? user.name : ""});
        });

        return userInfo;
    },

    isUserVisible: function(visitor, target) {
        var assistors = this.getUserData(target).assistors;
        return (assistors.length < gConfRuntime.HoroscopeFarmTreeAssistTimes) &&
            (-1 == assistors.indexOf(visitor));
    },

    assist: function(visitor, target) {
        var assistors = this.getUserData(target).assistors;
        if ((assistors.length >= gConfRuntime.HoroscopeFarmTreeAssistTimes) ||
                (-1 != assistors.indexOf(visitor))) {
            return false;
        }

        assistors.push(visitor);
        this.markDirty(target, 'assistors');
        this.save();
        return true;
    },

    getAward: function(uid) {
        var userData = this.getUserData(uid);
        if (userData.award || userData.assistors.length < gConfRuntime.HoroscopeFarmTreeAssistTimes) {
            return false;
        }

        userData.award = 1;
        this.markDirty(uid, 'award');
        this.save();
        return true;
    },
});
